//
//  WDAddressDetailController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/12/6.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDAddressDetailController.h"
#import "WDLinkMessage.h"
#import <MessageUI/MessageUI.h>
#import "WDADHeadView.h"
#import "WDSubordinate.h"
#import "WDButton.h"
#import "UIColor+WDColorExtension.h"
#import "WDPhoneAlertView.h"
#import "UIButton+WebCache.h"

#define WDHeadViewH 170
#define WDHeadViewMinH 0
#define WDNavColor(alpha) [UIColor colorWithRed:(((0xFD5722 & 0xFF0000) >> 16))/255.0 green:(((0xFD5722 & 0xFF00) >>8)/255.0) blue:((0xFD5722 &0xFF)/255.0) alpha:alpha]

@interface WDAddressDetailController () <MFMailComposeViewControllerDelegate, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) WDADHeadView *headView;
@property (nonatomic, strong) UITableView *tableView;
/** tableView原始偏移量y值 */
@property(assign, nonatomic) CGFloat oriOffsetY;
@property(nonatomic, weak) UILabel *nameLabel;
@property (assign, nonatomic) CGFloat footerH;
/** 下属信息数组 */
@property (nonatomic, strong) NSArray *subordinates;

@end

@implementation WDAddressDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadNavItemWithAction:@selector(clickBackBtn) btnImage:@"icon_back" btnSelImage:@"icon_back" title:nil];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self sendRequest];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 设置导航栏背景为透明
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new]forBarMetrics:UIBarMetricsDefault];
    // 隐藏导航栏底部黑线
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 当都设置为nil的时候，导航栏会使用默认的样式，即还原导航栏样式
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = nil;
}

#pragma mark - 点击事件
- (void)clickBackBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)clickSubordinate:(UIButton *)sender
{
    //解档联系人
    NSString *path = [WDCachePath stringByAppendingPathComponent:WDAddressFile];
    
    NSArray *linkMessages = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    
    WDLinkMessage *tempLink = nil;
    
    for (tempLink in linkMessages) {
        if ([tempLink.name isEqualToString:sender.titleLabel.text]) {
            break;
        } else {
            
            tempLink = nil;
        }
    }
    
    WDAddressDetailController *tempV = [[WDAddressDetailController alloc] init];
    
    tempV.linkMessage = tempLink;
    tempV.subordinate = [tempLink.is_responsible boolValue];
    
    
    [self.navigationController pushViewController:tempV animated:YES];
    
    
}

#pragma mark - 加载控件
- (void)setUpHeadView
{
    self.headView = [WDADHeadView adHeadView];
    
    self.headView.linkMessage = self.linkMessage;
    
    [self.view addSubview:self.headView];
    
    [self.headView makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.top.equalTo(0);
        
        make.height.equalTo(WDHeadViewH);
        
    }];
}

- (void)setUpTableView
{
    UITableView *tableView = [[UITableView alloc] init];
    tableView.frame = CGRectMake(0, 0, WDScreenW, WDScreenH - 64);
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    //当前scrollView的偏移量Y值
    self.oriOffsetY = -WDHeadViewH;
    //设置tableView额外滚动区域
    self.tableView.contentInset = UIEdgeInsetsMake(WDHeadViewH, 0, 0, 0);
    
    if (self.hasSubordinate  && self.subordinates.count) {
        UIView *footView = [self setUpFooterView];
        tableView.tableFooterView = footView;
        
        
    }
}

- (UIView *)setUpFooterView
{
    NSInteger cols = 5;
    CGFloat pading = 27;
    CGFloat btnW = 50;
    CGFloat btnH = 70;
    CGFloat subViewH = 37;
    CGFloat marginX = (WDScreenW - 2 * pading - btnW * cols) / (cols - 1);
    CGFloat marginY = 16;
    
    NSInteger rows = (self.subordinates.count % cols == 0) ? (self.subordinates.count / cols):(self.subordinates.count / cols + 1);
    CGFloat footerH = subViewH + 15 + (btnH + marginY) * rows;
    
    self.footerH = footerH;
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WDScreenW, footerH)];
    
    UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WDScreenW, subViewH)];
    subView.backgroundColor = ColorForRGB(0xf0f1f2);
    [footerView addSubview:subView];
    
    UILabel *subLabel = [[UILabel alloc] init];
    subLabel.text = @"下属";
    subLabel.font = [UIFont systemFontOfSize:14];
    [subView addSubview:subLabel];
    [subLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(16);
        make.centerY.equalTo(subView.centerY);
    }];
    
    UILabel *numberLabel = [[UILabel alloc] init];
    numberLabel.text = [NSString stringWithFormat:@"%zd人", self.subordinates.count];
    numberLabel.font = [UIFont systemFontOfSize:14];
    numberLabel.textColor = ColorForRGB(0xa8a9aa);
    [subView addSubview:numberLabel];
    [numberLabel makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(-16);
        make.centerY.equalTo(subView.centerY);
    }];
    
    for (int i = 0; i < self.subordinates.count; i++) {
        
        WDSubordinate *subordinate = self.subordinates[i];
        
        CGFloat btnX = pading + i % cols * (btnW + marginX);
        CGFloat btnY = marginY + subViewH + i / cols * (btnH + marginY);
        
        WDButton *btn = [WDButton buttonWithType:UIButtonTypeCustom];
        
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        
        if (subordinate.name.length > 4) {
            subordinate.name = [subordinate.name substringToIndex:4];
        }
        
        [btn setTitle:subordinate.name forState:UIControlStateNormal];
        
        btn.titleLabel.font = [UIFont systemFontOfSize:12];
        [btn setTitleColor:ColorForRGB(0x4c4c4c) forState:UIControlStateNormal];
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        
        [btn sd_setImageWithURL:[NSURL URLWithString:subordinate.image_url] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"defaultIcon"]];
        
        [btn addTarget:self action:@selector(clickSubordinate:) forControlEvents:UIControlEventTouchUpInside];
        
        [footerView addSubview:btn];
    }
    
    return footerView;
    
}

#pragma mark - 发网络请求
- (void)sendRequest
{
    if (self.hasSubordinate) {//有下属
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:WDURLLogin];
        
        if([cookiesdata length]) {
            
            NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
            
            NSHTTPCookie *cookie;
            
            for (cookie in cookies) {
                
                [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
            }
        }
        
        NSDictionary *parameters = @{
                                     @"emp_id":self.linkMessage.id,
                                     @"ctype":@3
                                     };
        
        NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLSubordinte];
        
        [manager POST:url parameters:parameters constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
//            WDLog(@"%@", responseObject);
            
            self.subordinates = [WDSubordinate mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            
            [self setUpTableView];
            [self setUpHeadView];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
//            WDLog(@"%@", error);
        }];
        
    } else {
        
        [self setUpTableView];
        [self setUpHeadView];
        
    }
}

#pragma mark - tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            UITableViewCell *cell = [[UITableViewCell alloc] init];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            
            cell.textLabel.textColor = ColorForRGB(0x4c4c4c);
            
            cell.imageView.image = [UIImage imageNamed:@"工作职位"];
            
            cell.textLabel.text = self.linkMessage.position_desc;
            
            return cell;
        }
            break;
            
        case 1:
        {
            UITableViewCell *cell = [[UITableViewCell alloc] init];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            
            cell.textLabel.textColor = ColorForRGB(0x4c4c4c);
            
            cell.imageView.image = [UIImage imageNamed:@"部门 (1)"];
            
            cell.textLabel.text = self.linkMessage.department_name;
            
            return cell;
        }
            break;
            
        case 2:
        {
            UITableViewCell *cell = [[UITableViewCell alloc] init];
            
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            
            cell.textLabel.textColor = ColorForRGB(0x4990e2);
            
            cell.imageView.image = [UIImage imageNamed:@"电话"];
            
            cell.textLabel.text = self.linkMessage.phone;
            
            return cell;
        }
            break;
            
        case 3:
        {
            UITableViewCell *cell = [[UITableViewCell alloc] init];
            
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            
            cell.textLabel.textColor = ColorForRGB(0x4990e2);
            
            cell.imageView.image = [UIImage imageNamed:@"邮箱"];
            
            cell.textLabel.text = self.linkMessage.account;
            
            return cell;
            }
            break;
            
        default:
            return nil;
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2) {//拨打电话
        
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        WDPhoneAlertView *alert = [[WDPhoneAlertView alloc] initWithTitle:@"呼叫" message:self.linkMessage.phone sureBtn:@"呼叫" cancleBtn:@"取消"];
        
        
        __weak typeof (self)weakSelf = self;
        alert.resultIndex = ^(NSInteger index){
            
            NSURL *openURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", weakSelf.linkMessage.phone]];
            
            [[UIApplication sharedApplication] openURL:openURL];
            
        };
        
        [alert show];
        
    } else if (indexPath.row == 3) {//发邮件
        
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        if ([MFMessageComposeViewController canSendText]) {
            
            MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
            
            picker.mailComposeDelegate = self;
            
            //主题
            [picker setSubject:@""];
            
            // 收件人邮箱
            NSArray *toRecipients = [NSArray arrayWithObject:self.linkMessage.account];
            
            [picker setToRecipients:toRecipients];
            
            
            if (picker) {
            
                [self presentViewController:picker animated:YES completion:nil];
            } else {
                
                
            }
            
        } else {
            
            [SVProgressHUD showInfoWithStatus:@"设备不支持"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [SVProgressHUD dismiss];
                
            });
        }
    }
}

#pragma mark - tableView滚动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //计算tableView滚动了多少
    
    //获取当前偏移量
    CGFloat currentOffsetY = scrollView.contentOffset.y;
    
    CGFloat delta = currentOffsetY - self.oriOffsetY;
    
    //计算头部视图的高度
    CGFloat h = WDHeadViewH - delta;
    if (h < WDHeadViewMinH) {
        h = WDHeadViewMinH;
    }
    
    //修改头部视图的高度，有视觉差效果
    [self.headView updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(h);
    }];
    
    //处理导航条业务逻辑
    //计算透明度
    CGFloat alpha = delta / (WDHeadViewH - WDHeadViewMinH);
    
    if (alpha > 1) {
        alpha = 1;
    }
    WDLog(@"%f", alpha);
    //设置导航条背景图片
    //根据alpha值生成图片
    UIImage *image = [UIImage imageWithColor:WDNavColor(alpha)];
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    
    //设置导航条的文字
    self.nameLabel.textColor = [UIColor colorWithWhite:1 alpha:alpha];
}

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    NSString *msg;
    
    switch (result)
    {
        case MFMailComposeResultCancelled:
        {
            msg = @"邮件发送取消";
        }
            break;
            
        case MFMailComposeResultSaved:
        {
            msg = @"邮件保存成功";
            
            [SVProgressHUD showSuccessWithStatus:msg];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [SVProgressHUD dismiss];
                
            });
        }
            break;
            
        case MFMailComposeResultSent:
        {
            msg = @"邮件发送成功";
            
            [SVProgressHUD showSuccessWithStatus:msg];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [SVProgressHUD dismiss];
                
            });
        }
            break;
            
        case MFMailComposeResultFailed:
        {
            msg = @"邮件发送失败";
            
            [SVProgressHUD showErrorWithStatus:msg];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [SVProgressHUD dismiss];
                
            });
        }
            break;
            
        default:
            break;
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
